//
//  CustomScrollView.m
//  eeeeeeeeeeee
//
//  Created by 陶秋安 on 16/4/1.
//  Copyright © 2016年 孙智慧. All rights reserved.
//

#import "CustomScrollView.h"

@implementation CustomScrollView

- (void)loadImageData
{
    _imageCount = _mArrayImageData.count;
    
    [self downloadImg];
}

-(void) downloadImg
{
    
    for (NSInteger i=0; i<[_mArrayImageData count]; i++)
    {
        NSDictionary *dict= [_mArrayImageData objectAtIndex:i];
        
        NSString *imgName=[dict objectForKey:@"pathName"];
        
        NSString *imgPath= [dict objectForKey:@"path"];
        
        if(![Common checkLanchExist:imgName])
        {
            //            //这里把imageBlock当做了一个变量，它封装了一段代码，这段代码在-(void)AdImg:(NSArray*)arr中
            //            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void)
            //                           {
            NSData * data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imgPath]];
            
            [data writeToFile:[FxGlobal getCacheImage:imgName] atomically:YES];
            
            //                           });
        }
        
    }
}

- (void)addScrollView
{
    _scrV = [[UIScrollView alloc] init];
    
    _scrV.translatesAutoresizingMaskIntoConstraints=NO;
    _scrV.pagingEnabled = YES;
    _scrV.showsHorizontalScrollIndicator = NO;
    _scrV.delegate = self;
    
    
    [self addSubview:_scrV];
    
    //ImageView左侧与父视图左侧对齐
    NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:_scrV attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f];
    [self addConstraint:leftConstraint];
    
    //ImageView右侧与父视图右侧对齐
    NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:_scrV attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1.0f constant:0.0f];
    [self addConstraint:rightConstraint];
    
    //ImageView顶部与父视图顶部对齐
    NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:_scrV attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self  attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f];
    [self addConstraint:topConstraint];
    //ImageView底部与父视图顶部对齐
    NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:_scrV attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0f constant:0.0f];
    [self addConstraint:bottomConstraint];
    
}

- (void)addImageViewsToScrollView
{
    //图片视图；左边
    _imgVLeft = [[UIImageView alloc]init];
    _imgVLeft.translatesAutoresizingMaskIntoConstraints=NO;
    _imgVLeft.contentMode = UIViewContentModeScaleAspectFit;
    
    [_scrV addSubview:_imgVLeft];
    [self setPostion:0 andView:_imgVLeft andHost:_scrV];
    [Common createActivityView:_imgVLeft];
    
    //图片视图；中间
    _imgVCenter = [[UIImageView alloc]init];
    _imgVCenter.translatesAutoresizingMaskIntoConstraints=NO;
    _imgVCenter.contentMode = UIViewContentModeScaleAspectFit;
    
    [_scrV addSubview:_imgVCenter];
    [self setPostion:1 andView:_imgVCenter andHost:_scrV];
    [Common createActivityView:_imgVCenter];
    
    //图片视图；右边
    _imgVRight = [[UIImageView alloc]init];
    _imgVRight.translatesAutoresizingMaskIntoConstraints=NO;
    _imgVRight.contentMode = UIViewContentModeScaleAspectFit;
    
    
    [_scrV addSubview:_imgVRight];
    [self setPostion:2 andView:_imgVRight andHost:_scrV];
    [Common createActivityView:_imgVRight];
}

-(void) setPostion:(NSInteger) i andView:(UIView *) view andHost:(UIView *)host
{
    if (i==0) {
        //ImageView左侧与父视图左侧对齐
        NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:host attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f];
        [host addConstraint:leftConstraint];
    }
    //ImageView顶部与父视图顶部对齐
    NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:host attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f];
    
    //ImageView底部与父视图顶部对齐
    NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:host attribute:NSLayoutAttributeBottom multiplier:1.0f constant:0.0f];
    if(i==1)
    {
        //ImageView高度为父视图高度
        NSLayoutConstraint* heightConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:host attribute:NSLayoutAttributeHeight multiplier:1.0f constant:0.0f];
        
        //ImageView宽度为父视图宽度
        NSLayoutConstraint* widthConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:host attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f];

        [host addConstraints:@[heightConstraint,widthConstraint]];
    }
    else
    {
        //ImageView高度为父视图高度
        NSLayoutConstraint* heightConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:host attribute:NSLayoutAttributeHeight multiplier:1.0f constant:-10.0f];
        
        //ImageView宽度为父视图宽度
        NSLayoutConstraint* widthConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:host attribute:NSLayoutAttributeWidth multiplier:1.0f constant:-10.0f];
        
        [host addConstraints:@[heightConstraint,widthConstraint]];
    }
    
    //iOS 6.0或者7.0调用addConstraints
    [host addConstraints:@[bottomConstraint, topConstraint]];
    
    if(i>0)
    {
        //imageView 右边距和父视图对齐 以便确定父视图的内容边界
        UIImageView *imgView=(UIImageView * )host.subviews[i-1];
        NSLayoutConstraint *spaceConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:imgView attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:-10.0f];
        
        [host addConstraint:spaceConstraint];
    }
    if(i==2)
    {
        
        NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:host attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:0.0f];
        
        [host addConstraint:constraint];
    }
}


- (void)addPageControl
{
    _pageC = [[UIPageControl alloc]init];
    
    CGSize size= [_pageC sizeForNumberOfPages:_imageCount]; //根据页数返回 UIPageControl 合适的大小
    
    _pageC.numberOfPages = _imageCount;
    _pageC.pageIndicatorTintColor = [UIColor whiteColor];
    _pageC.currentPageIndicatorTintColor = [UIColor redColor];
    _pageC.userInteractionEnabled = NO; //设置是否允许用户交互；默认值为 YES，当为 YES 时，针对点击控件区域左（当前页索引减一，最小为0）右（当前页索引加一，最大为总数减一），可以编写 UIControlEventValueChanged 的事件处理方法
    _pageC.translatesAutoresizingMaskIntoConstraints=NO;
    
    
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self addSubview:_pageC];
        
        NSLayoutConstraint *centerConstraint = [NSLayoutConstraint constraintWithItem:_pageC attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f];
        
        [self addConstraint:centerConstraint];
        
        //ImageView底部与父视图顶部对齐
        NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:_pageC attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0f constant:10 ];
        
        [self addConstraint:bottomConstraint];
        
        //ImageView高度为父视图高度
        NSLayoutConstraint* heightConstraint = [NSLayoutConstraint constraintWithItem:_pageC attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:size.height];
        [self addConstraint:heightConstraint];
        
        //ImageView宽度为父视图宽度
        NSLayoutConstraint* widthConstraint = [NSLayoutConstraint constraintWithItem:_pageC attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:size.width];
        [self addConstraint:widthConstraint];
        
    });
    
}

- (void)setInfoByCurrentImageIndex:(NSUInteger)currentImageIndex
{
    NSDictionary * dict= [_mArrayImageData objectAtIndex:currentImageIndex];
    
    NSString * imgName =[dict objectForKey:@"pathName"];
    
    NSString * imgPath= [dict objectForKey:@"path"];
    
    NSString * filePath = [FxGlobal getCacheImage:imgName];
    
    dispatch_async(dispatch_get_main_queue(), ^(void){
        
        UIImage * img= [UIImage imageWithContentsOfFile:filePath];
        
        [_imgVCenter setImage:img];
        
        [Common stopActivityView:_imgVCenter];
    });
    
    dict= [_mArrayImageData objectAtIndex:((_currentImageIndex - 1+_imageCount) % _imageCount)];
    
    imgName =[dict objectForKey:@"pathName"];
    
    imgPath= [dict objectForKey:@"path"];
    
    filePath = [FxGlobal getCacheImage:imgName];
    
    
    dispatch_async(dispatch_get_main_queue(), ^(void){
        
        UIImage * img= [UIImage imageWithContentsOfFile:filePath];
        
        [_imgVLeft setImage:img];
        
        [Common stopActivityView:_imgVLeft];
        
    });
    
    dict= [_mArrayImageData objectAtIndex:((_currentImageIndex + 1) % _imageCount)];
    
    imgName =[dict objectForKey:@"pathName"];
    
    imgPath= [dict objectForKey:@"path"];
    
    filePath = [FxGlobal getCacheImage:imgName];
    
    dispatch_sync(dispatch_get_main_queue(), ^{
        
        UIImage * img= [UIImage imageWithContentsOfFile:filePath];
        
        [_imgVRight setImage:img];
        
        [Common stopActivityView:_imgVRight];
    });
    
    _pageC.currentPage = currentImageIndex;
    
}

- (void)setInfoByCurrentImageIndexNoSync:(NSUInteger)currentImageIndex
{
    NSDictionary *dict= [_mArrayImageData objectAtIndex:currentImageIndex];
    
    NSString *imgName =[dict objectForKey:@"pathName"];
    
    NSString *imgPath= [dict objectForKey:@"path"];
    
    NSString *filePath = [FxGlobal getCacheImage:imgName];
    
    UIImage *img= [UIImage imageWithContentsOfFile:filePath];
    
    [_imgVCenter setImage:img];
    
    dict= [_mArrayImageData objectAtIndex:((_currentImageIndex - 1 + _imageCount) % _imageCount)];
    
    imgName =[dict objectForKey:@"pathName"];
    
    imgPath= [dict objectForKey:@"path"];
    
    filePath = [FxGlobal getCacheImage:imgName];
    
    img= [UIImage imageWithContentsOfFile:filePath];
    
    [_imgVLeft setImage:img];
    
    dict= [_mArrayImageData objectAtIndex:((_currentImageIndex + 1) % _imageCount)];
    
    imgName =[dict objectForKey:@"pathName"];
    
    imgPath= [dict objectForKey:@"path"];
    
    filePath = [FxGlobal getCacheImage:imgName];
    
    img= [UIImage imageWithContentsOfFile:filePath];
    
    [_imgVRight setImage:img];
    
    _pageC.currentPage = currentImageIndex;
    
}

- (void)setDefaultInfo
{
    _currentImageIndex = 0;
    
    [self setInfoByCurrentImageIndex:_currentImageIndex];
    
    dispatch_sync(dispatch_get_main_queue(), ^{
        
        _scrV.contentOffset = CGPointMake(kWidthOfScreen, 0.0);
    });
    
}

- (void)reloadImage
{
    
    CGPoint contentOffset = [_scrV contentOffset];
    
    if (contentOffset.x >= kWidthOfScreen)//向左滑动
    {
        _currentImageIndex = (_currentImageIndex + 1) % _imageCount;
        
    }
    else if (contentOffset.x < kWidthOfScreen)//向右滑动
    {
        _currentImageIndex = (_currentImageIndex - 1 + _imageCount) % _imageCount;
    }
    
    [self setInfoByCurrentImageIndexNoSync:_currentImageIndex];
}

- (void)layoutUI
{
    [self addScrollView];
    
    [self addImageViewsToScrollView];
    
}

-(void)loadData:(NSArray *) paramArrayImageData
{
    _mArrayImageData= paramArrayImageData;
    
    [self loadImageData];
    
    [self addPageControl];
    
    [self setDefaultInfo];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(_imageCount>0)
    {
        [self reloadImage];
        
        _scrV.contentOffset = CGPointMake(kWidthOfScreen, 0.0);
        
        _pageC.currentPage = _currentImageIndex;
    }
    
}

@end
